<template>
  <view class="leave-approve-page">
    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <u-loading-icon mode="circle" size="40" color="#007bff"></u-loading-icon>
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 错误状态 -->
    <view v-else-if="errorMessage" class="error-container">
      <u-empty 
        text="获取详情失败" 
        icon="error-circle"
        mode="data"
      />
      <u-button 
        type="primary" 
        text="重新加载" 
        @click="loadLeaveDetail"
        class="retry-button"
      />
    </view>

    <!-- 审批内容 -->
    <view v-else-if="leaveDetail" class="approve-content">
      <!-- 状态卡片 -->
      <view class="status-section">
        <view class="status-card">
          <view class="status-header">
            <text class="status-title">{{ getLeaveTypeText(leaveDetail.leaveType) }}</text>
            <view class="status-tag">
              <u-tag 
                :text="getStatusText(leaveDetail.status)" 
                :type="getStatusType(leaveDetail.status)" 
                size="mini"
              />
            </view>
          </view>
          <view class="status-desc">{{ getStatusDescription(leaveDetail.status) }}</view>
        </view>
      </view>

      <!-- 基本信息 -->
      <view class="info-section">
        <view class="info-card">
          <view class="card-title">基本信息</view>
          <view class="info-list">
            <view class="info-item">
              <text class="info-label">申请人</text>
              <text class="info-value">{{ leaveDetail.userName || '未知' }}</text>
            </view>
            
            <view class="info-item">
              <text class="info-label">请假类型</text>
              <text class="info-value">{{ getLeaveTypeText(leaveDetail.leaveType) }}</text>
            </view>
            
            <view class="info-item">
              <text class="info-label">请假时间</text>
              <text class="info-value">{{ leaveDetail.startDate }} 至 {{ leaveDetail.endDate }}</text>
            </view>
            
            <view class="info-item" v-if="leaveDetail.startTime || leaveDetail.endTime">
              <text class="info-label">具体时间</text>
              <text class="info-value">
                {{ leaveDetail.startTime || '--' }} 至 {{ leaveDetail.endTime || '--' }}
              </text>
            </view>
            
            <view class="info-item">
              <text class="info-label">请假天数</text>
              <text class="info-value">{{ leaveDetail.days }}天</text>
            </view>
            
            <view class="info-item">
              <text class="info-label">申请时间</text>
              <text class="info-value">{{ formatDateTime(leaveDetail.createTime) }}</text>
            </view>
            
            <view class="info-item" v-if="leaveDetail.propertyCompanyName">
              <text class="info-label">物业公司</text>
              <text class="info-value">{{ leaveDetail.propertyCompanyName }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 详细信息 -->
      <view class="detail-section">
        <view class="detail-card">
          <view class="card-title">详细信息</view>
          <view class="detail-list">
            <view class="detail-item">
              <text class="detail-label">请假原因</text>
              <text class="detail-value">{{ leaveDetail.reason || '--' }}</text>
            </view>
            
            <view class="detail-item" v-if="leaveDetail.remark">
              <text class="detail-label">备注</text>
              <text class="detail-value">{{ leaveDetail.remark }}</text>
            </view>
            
            <view class="detail-item" v-if="leaveDetail.emergencyContact">
              <text class="detail-label">紧急联系人</text>
              <text class="detail-value">{{ leaveDetail.emergencyContact }}</text>
            </view>
            
            <view class="detail-item" v-if="leaveDetail.emergencyPhone">
              <text class="detail-label">紧急联系电话</text>
              <text class="detail-value">{{ leaveDetail.emergencyPhone }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 附件信息 -->
      <view class="attachment-section" v-if="hasAttachments">
        <view class="attachment-card">
          <view class="card-title">附件</view>
          <view class="attachment-list">
            <!-- 单个附件URL -->
            <view class="attachment-item" v-if="leaveDetail.attachmentUrl">
              <AppImagePreview 
                :src="leaveDetail.attachmentUrl" 
                :alt="'请假申请附件'"
                class="attachment-image"
              />
            </view>
            
            <!-- 多个附件列表 -->
            <view class="attachment-item" v-for="(attachment, index) in attachmentList" :key="index">
              <AppImagePreview 
                :src="attachment.url || attachment" 
                :alt="`附件${index + 1}`"
                class="attachment-image"
              />
            </view>
          </view>
        </view>
      </view>

      <!-- 审批表单 -->
      <view class="approve-section">
        <view class="approve-card">
          <view class="card-title">审批意见</view>
          <view class="approve-form">
            <view class="form-item">
              <text class="form-label">审批结果</text>
              <view class="radio-group">
                <u-radio-group v-model="approveForm.status" direction="row">
                  <u-radio 
                    :customStyle="{ marginRight: '20px' }"
                    :label="2" 
                    name="status"
                    activeColor="#19be6b"
                  >
                    批准
                  </u-radio>
                  <u-radio 
                    :label="3" 
                    name="status"
                    activeColor="#fa3534"
                  >
                    拒绝
                  </u-radio>
                </u-radio-group>
              </view>
            </view>
            
            <view class="form-item">
              <text class="form-label">审批备注</text>
              <u-textarea 
                v-model="approveForm.remark"
                placeholder="请输入审批备注（可选）"
                :maxlength="200"
                :count="true"
                :autoHeight="true"
                class="approve-textarea"
              ></u-textarea>
            </view>
          </view>
        </view>
      </view>

      <!-- 操作按钮 -->
      <view class="action-section">
        <view class="action-buttons">
          <u-button 
            type="info" 
            text="返回" 
            :custom-style="{ marginRight: '12px', flex: 1 }"
            @click="handleBack"
          ></u-button>
          <u-button 
            type="primary" 
            text="提交审批" 
            :loading="approving"
            :custom-style="{ flex: 1 }"
            @click="submitApprove"
          ></u-button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { ref, onMounted, reactive, computed } from 'vue'
import { getLeaveDetail, approveLeave } from '@/api/leave'
import { useAuthStore } from '@/store/auth'
import AppImagePreview from '@/components/AppImagePreview.vue'

export default {
  name: 'LeaveApprove',
  components: {
    AppImagePreview
  },
  setup() {
    // 响应式数据
    const loading = ref(false)
    const errorMessage = ref('')
    const leaveDetail = ref(null)
    const approving = ref(false)
    
    // 审批表单
    const approveForm = reactive({
      status: 2, // 默认批准
      remark: ''
    })

    // 获取页面参数
    const leaveId = ref(null)

    // 计算属性：是否有附件
    const hasAttachments = computed(() => {
      if (!leaveDetail.value) return false
      
      // 检查单个附件URL
      if (leaveDetail.value.attachmentUrl) return true
      
      // 检查附件列表
      if (leaveDetail.value.attachments && Array.isArray(leaveDetail.value.attachments) && leaveDetail.value.attachments.length > 0) {
        return true
      }
      
      return false
    })

    // 计算属性：附件列表
    const attachmentList = computed(() => {
      if (!leaveDetail.value) return []
      
      // 如果有附件列表
      if (leaveDetail.value.attachments && Array.isArray(leaveDetail.value.attachments)) {
        return leaveDetail.value.attachments
      }
      
      return []
    })

    // 获取请假详情
    const loadLeaveDetail = async () => {
      console.log('loadLeaveDetail方法被调用')
      console.log('当前leaveId.value:', leaveId.value)
      
      if (!leaveId.value) {
        console.error('leaveId.value为空')
        errorMessage.value = '请假记录ID无效'
        return
      }

      try {
        console.log('开始设置loading状态')
        loading.value = true
        errorMessage.value = ''
        
        console.log('调用获取请假记录详情API, ID:', leaveId.value)
        
        // 确保用户已登录
        const authStore = useAuthStore()
        if (!authStore.userInfo || !authStore.userInfo.id) {
          errorMessage.value = '用户未登录，请重新登录'
          return
        }
        
        console.log('当前用户信息:', authStore.userInfo)
        
        const result = await getLeaveDetail(leaveId.value)
        
        console.log('获取请假记录详情API响应:', result)
        
               if (result.success && result.data) {
                 leaveDetail.value = result.data
                 console.log('获取请假详情成功:', leaveDetail.value)
                 console.log('详情数据结构分析:')
                 console.log('- 基本信息:', {
                   id: leaveDetail.value.id,
                   userId: leaveDetail.value.userId,
                   userName: leaveDetail.value.userName,
                   leaveType: leaveDetail.value.leaveType,
                   leaveTypeName: leaveDetail.value.leaveTypeName,
                   startDate: leaveDetail.value.startDate,
                   endDate: leaveDetail.value.endDate,
                   days: leaveDetail.value.days,
                   reason: leaveDetail.value.reason,
                   status: leaveDetail.value.status,
                   statusName: leaveDetail.value.statusName
                 })
                 console.log('- 附件信息:', {
                   attachmentUrl: leaveDetail.value.attachmentUrl,
                   attachments: leaveDetail.value.attachments,
                   hasAttachments: hasAttachments.value,
                   attachmentList: attachmentList.value
                 })
                 console.log('- 其他字段:', {
                   remark: leaveDetail.value.remark,
                   emergencyContact: leaveDetail.value.emergencyContact,
                   emergencyPhone: leaveDetail.value.emergencyPhone,
                   propertyCompanyName: leaveDetail.value.propertyCompanyName,
                   createTime: leaveDetail.value.createTime
                 })
               } else {
                 errorMessage.value = result.message || '获取请假详情失败'
                 console.error('获取详情失败，错误信息:', result.message)
               }
      } catch (error) {
        console.error('获取请假详情失败:', error)
        errorMessage.value = '网络错误，请重试'
      } finally {
        loading.value = false
      }
    }

    // 提交审批
    const submitApprove = async () => {
      if (!leaveDetail.value) {
        uni.showToast({
          title: '请假记录不存在',
          icon: 'none'
        })
        return
      }

      try {
        approving.value = true
        
        const authStore = useAuthStore()
        const currentUserId = authStore.userInfo?.id
        
        if (!currentUserId) {
          uni.showToast({
            title: '用户信息异常，请重新登录',
            icon: 'none'
          })
          return
        }

        const approveData = {
          status: approveForm.status,
          approveRemark: approveForm.remark
        }

        console.log('提交审批数据:', approveData)
        
        const result = await approveLeave(leaveDetail.value.id, approveData)
        
        if (result.success) {
          uni.showToast({
            title: approveForm.status === 2 ? '审批通过' : '审批拒绝',
            icon: 'success'
          })
          
          // 返回上一页
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        } else {
          uni.showToast({
            title: result.message || '审批失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('审批请假申请失败:', error)
        uni.showToast({
          title: '审批失败，请重试',
          icon: 'none'
        })
      } finally {
        approving.value = false
      }
    }

    // 返回上一页
    const handleBack = () => {
      uni.navigateBack()
    }

    // 获取请假类型文本
    const getLeaveTypeText = (type) => {
      const typeMap = {
        'sick': '病假',
        'personal': '事假',
        'annual': '年假',
        'maternity': '产假',
        'paternity': '陪产假',
        'marriage': '婚假',
        'funeral': '丧假'
      }
      return typeMap[type] || type || '未知'
    }

    // 获取状态文本
    const getStatusText = (status) => {
      const statusMap = {
        1: '待审批',
        2: '已通过',
        3: '已拒绝',
        4: '已撤销'
      }
      return statusMap[status] || '未知'
    }

    // 获取状态类型
    const getStatusType = (status) => {
      const typeMap = {
        1: 'warning',
        2: 'success',
        3: 'error',
        4: 'info'
      }
      return typeMap[status] || 'info'
    }

    // 获取状态描述
    const getStatusDescription = (status) => {
      const descMap = {
        1: '等待审批中，请耐心等待',
        2: '审批已通过，请假生效',
        3: '审批被拒绝，请联系审批人',
        4: '申请已撤销'
      }
      return descMap[status] || '状态未知'
    }

    // 格式化日期时间
    const formatDateTime = (dateTime) => {
      if (!dateTime) return '--'
      const date = new Date(dateTime)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }

    // 页面加载
    onMounted(() => {
      console.log('审批页面开始加载...')
      try {
        // 获取页面参数 - 兼容H5和App环境
        let pageId = null
        
        // 方法1：通过getCurrentPages获取
        const pages = getCurrentPages()
        console.log('页面栈:', pages)
        
        if (pages && pages.length > 0) {
          const currentPage = pages[pages.length - 1]
          console.log('当前页面:', currentPage)
          
          if (currentPage && currentPage.options) {
            const options = currentPage.options
            console.log('页面参数(options):', options)
            pageId = options.id
          }
        }
        
        // 方法2：通过URL解析获取（H5环境备用方案）
        if (!pageId) {
          console.log('尝试从URL解析参数...')
          const url = window.location.href
          console.log('当前URL:', url)
          
          const urlParams = new URLSearchParams(window.location.search)
          pageId = urlParams.get('id')
          console.log('URL参数解析结果:', pageId)
        }
        
        // 方法3：通过hash解析获取（uni-app H5环境）
        if (!pageId) {
          console.log('尝试从hash解析参数...')
          const hash = window.location.hash
          console.log('当前hash:', hash)
          
          if (hash.includes('?')) {
            const hashParams = new URLSearchParams(hash.split('?')[1])
            pageId = hashParams.get('id')
            console.log('hash参数解析结果:', pageId)
          }
        }
        
        console.log('最终获取到的ID:', pageId)
        
        if (pageId) {
          leaveId.value = parseInt(pageId)
          console.log('获取到请假ID:', leaveId.value)
          console.log('开始调用loadLeaveDetail...')
          loadLeaveDetail()
        } else {
          console.error('所有方法都无法获取到ID参数')
          errorMessage.value = '缺少请假记录ID参数'
        }
      } catch (error) {
        console.error('页面初始化失败:', error)
        errorMessage.value = '页面初始化失败，请重试'
      }
    })

    return {
      loading,
      errorMessage,
      leaveDetail,
      approving,
      approveForm,
      hasAttachments,
      attachmentList,
      loadLeaveDetail,
      submitApprove,
      handleBack,
      getLeaveTypeText,
      getStatusText,
      getStatusType,
      getStatusDescription,
      formatDateTime
    }
  }
}
</script>

<style lang="scss" scoped>
.leave-approve-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 120rpx;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400rpx;
  
  .loading-text {
    margin-top: 20rpx;
    color: #666;
    font-size: 28rpx;
  }
}

.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400rpx;
  
  .retry-button {
    margin-top: 20rpx;
  }
}

.approve-content {
  padding: 20rpx;
}

.status-section {
  margin-bottom: 20rpx;
  
  .status-card {
    background: #fff;
    border-radius: 16rpx;
    padding: 30rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
    
    .status-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16rpx;
      
      .status-title {
        font-size: 32rpx;
        font-weight: 600;
        color: #333;
      }
    }
    
    .status-desc {
      font-size: 26rpx;
      color: #666;
      line-height: 1.5;
    }
  }
}

.info-section, .detail-section, .attachment-section, .approve-section {
  margin-bottom: 20rpx;
  
  .info-card, .detail-card, .attachment-card, .approve-card {
    background: #fff;
    border-radius: 16rpx;
    padding: 30rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
    
    .card-title {
      font-size: 30rpx;
      font-weight: 600;
      color: #333;
      margin-bottom: 24rpx;
      padding-bottom: 16rpx;
      border-bottom: 1rpx solid #f0f0f0;
    }
  }
}

.info-list, .detail-list {
  .info-item, .detail-item {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    padding: 16rpx 0;
    border-bottom: 1rpx solid #f8f8f8;
    
    &:last-child {
      border-bottom: none;
    }
    
    .info-label, .detail-label {
      font-size: 28rpx;
      color: #666;
      min-width: 140rpx;
      flex-shrink: 0;
    }
    
    .info-value, .detail-value {
      font-size: 28rpx;
      color: #333;
      text-align: right;
      flex: 1;
      word-break: break-all;
    }
  }
}

.attachment-list {
  .attachment-item {
    .attachment-image {
      width: 100%;
      max-width: 400rpx;
      height: 300rpx;
      border-radius: 8rpx;
      object-fit: cover;
    }
  }
}

.approve-form {
  .form-item {
    margin-bottom: 30rpx;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .form-label {
      display: block;
      font-size: 28rpx;
      color: #333;
      margin-bottom: 16rpx;
      font-weight: 500;
    }
    
    .radio-group {
      margin-bottom: 16rpx;
    }
    
    .approve-textarea {
      background: #f8f9fa;
      border-radius: 8rpx;
    }
  }
}

.action-section {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  padding: 20rpx 30rpx;
  border-top: 1rpx solid #eee;
  box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.1);
  
  .action-buttons {
    display: flex;
    gap: 12rpx;
  }
}

/* 响应式设计 */
@media screen and (max-width: 750rpx) {
  .approve-content {
    padding: 16rpx;
  }
  
  .status-section, .info-section, .detail-section, .attachment-section, .approve-section {
    margin-bottom: 16rpx;
    
    .status-card, .info-card, .detail-card, .attachment-card, .approve-card {
      padding: 24rpx;
      border-radius: 12rpx;
    }
  }
  
  .action-section {
    padding: 16rpx 24rpx;
  }
}
</style>
